package com.zhxy.gps.tm;

import java.util.List;

import com.zhxy.gps.gateway.GatewayMessageContext;
import com.zhxy.gps.gateway.TerminalGateway;
import com.zhxy.gps.terminal.Terminal;
import com.zhxy.gps.terminal.message.AbstractMessage;
import com.zhxy.gps.terminal.message.ReplyMessage;
import com.zhxy.util.UncaughtException;
import com.zhxy.util.async.ResultHandler;
import com.zhxy.util.bean.EventProvider;
import com.zhxy.util.message.AsyncMessageProcessor;

public class DefaultTerminalManager implements TerminalManager {
	
	private EventProvider<TerminalManagerListener> event = new EventProvider<TerminalManagerListener>();
	
	private List<TerminalGateway> gateways;

	public List<TerminalGateway> getGateways() {
		return gateways;
	}

	public void setGateways(List<TerminalGateway> gateways) {
		
		if (gateways != null && gateways.size() > 1) {
			throw new IllegalArgumentException("暂时只支持一个网关");
		}
		
		this.gateways = gateways;
		if (gateways != null) {
			MessageProcessor processor = new MessageProcessor();
			for (TerminalGateway gateway : gateways) {
				gateway.setProcessor(processor);
			}
		}
	}
	
	@Override
	public void addTerminalManagerListener(TerminalManagerListener listener) {
		event.addEventListener(listener);
	}
	
	@Override
	public void removeTerminalManagerListener(TerminalManagerListener listener) {
		event.removeEventListener(listener);
	}
	
	public void send(String deviceSerial, AbstractMessage message, ResultHandler<ReplyMessage> handler) {
		
		TerminalGateway gateway = getGateway(deviceSerial);
		if (gateway == null)
			throw new UncaughtException("终端不在线");
		gateway.send(deviceSerial, message, handler);
	}

	@Override
	public Object status(String deviceSerial, String name) {
		
		if (STATUS_ONLINE.equals(name)) {
			return getGateway(deviceSerial) != null;
		}
		// TODO Auto-generated method stub
		return null;
	}
	
	protected String getTerminalGroup(Terminal terminal) {
		return "normal";
	}
	
	
	private TerminalGateway getGateway(String deviceSerial) {
		for (TerminalGateway gateway : gateways) {
			boolean online = (Boolean)gateway.status(deviceSerial, TerminalGateway.STATUS_ONLINE);
			if (online) {
				return gateway;
			}
		}
		return null;
	}

	/**
	 * 处理网关的消息
	 * @author 刘勉
	 *
	 */
	class MessageProcessor implements AsyncMessageProcessor<GatewayMessageContext, AbstractMessage> {
		@Override
		public void process(GatewayMessageContext context,
				AbstractMessage message, ResultHandler<AbstractMessage> handler) {
			
			Terminal terminal = context.getTerminal();
			String group = getTerminalGroup(terminal);
			Terminal t = new Terminal(terminal.getDeviceSerial(), group);
			
			for (TerminalManagerListener listener : event.toList()) {
				listener.message(t, message);
			}
			
		}
	}

}
